using System;
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using JGSY.CMS.LowCode.Platform.Application.Interfaces;

namespace JGSY.CMS.LowCode.Platform.Application.Services
{
    /// <summary>
    /// 用户上下文服务实现
    /// 提供当前用户信息的获取和管理功能
    /// </summary>
    public class UserContextService : IUserContextService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ILogger<UserContextService> _logger;

        public UserContextService(
            IHttpContextAccessor httpContextAccessor,
            ILogger<UserContextService> logger)
        {
            _httpContextAccessor = httpContextAccessor;
            _logger = logger;
        }

        /// <summary>
        /// 获取当前用户ID
        /// </summary>
        public long? GetCurrentUserId()
        {
            try
            {
                var httpContext = _httpContextAccessor.HttpContext;
                if (httpContext?.User?.Identity?.IsAuthenticated == true)
                {
                    var userIdClaim = httpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
                    if (long.TryParse(userIdClaim, out long userId))
                    {
                        return userId;
                    }

                    // 尝试其他可能的用户ID声明
                    userIdClaim = httpContext.User.FindFirst("userId")?.Value;
                    if (long.TryParse(userIdClaim, out userId))
                    {
                        return userId;
                    }

                    userIdClaim = httpContext.User.FindFirst("id")?.Value;
                    if (long.TryParse(userIdClaim, out userId))
                    {
                        return userId;
                    }
                }

                // 如果没有认证用户，返回系统默认用户ID
                _logger.LogDebug("未找到当前用户，返回系统默认用户ID");
                return 1; // 系统默认用户ID
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "获取当前用户ID时发生异常");
                return 1; // 系统默认用户ID
            }
        }

        /// <summary>
        /// 获取当前用户名
        /// </summary>
        public string? GetCurrentUserName()
        {
            try
            {
                var httpContext = _httpContextAccessor.HttpContext;
                if (httpContext?.User?.Identity?.IsAuthenticated == true)
                {
                    return httpContext.User.Identity.Name;
                }
                return "System";
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "获取当前用户名时发生异常");
                return "System";
            }
        }

        /// <summary>
        /// 获取当前用户邮箱
        /// </summary>
        public string? GetCurrentUserEmail()
        {
            try
            {
                var httpContext = _httpContextAccessor.HttpContext;
                if (httpContext?.User?.Identity?.IsAuthenticated == true)
                {
                    return httpContext.User.FindFirst(ClaimTypes.Email)?.Value;
                }
                return null;
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "获取当前用户邮箱时发生异常");
                return null;
            }
        }

        /// <summary>
        /// 获取当前用户角色
        /// </summary>
        public IEnumerable<string> GetCurrentUserRoles()
        {
            try
            {
                var httpContext = _httpContextAccessor.HttpContext;
                if (httpContext?.User?.Identity?.IsAuthenticated == true)
                {
                    return httpContext.User.FindAll(ClaimTypes.Role).Select(c => c.Value);
                }
                return new[] { "Anonymous" };
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "获取当前用户角色时发生异常");
                return new[] { "Anonymous" };
            }
        }

        /// <summary>
        /// 检查当前用户是否有指定权限
        /// </summary>
        public bool HasPermission(string permission)
        {
            try
            {
                var httpContext = _httpContextAccessor.HttpContext;
                if (httpContext?.User?.Identity?.IsAuthenticated == true)
                {
                    // 检查权限声明
                    return httpContext.User.HasClaim("permission", permission) ||
                           httpContext.User.HasClaim("permissions", permission) ||
                           httpContext.User.IsInRole("Admin"); // 管理员拥有所有权限
                }
                return false;
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "检查用户权限时发生异常: {Permission}", permission);
                return false;
            }
        }

        /// <summary>
        /// 检查当前用户是否有指定角色
        /// </summary>
        public bool IsInRole(string role)
        {
            try
            {
                var httpContext = _httpContextAccessor.HttpContext;
                if (httpContext?.User?.Identity?.IsAuthenticated == true)
                {
                    return httpContext.User.IsInRole(role);
                }
                return false;
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "检查用户角色时发生异常: {Role}", role);
                return false;
            }
        }

        /// <summary>
        /// 获取当前租户ID
        /// </summary>
        public string? GetCurrentTenantId()
        {
            try
            {
                var httpContext = _httpContextAccessor.HttpContext;
                if (httpContext?.User?.Identity?.IsAuthenticated == true)
                {
                    return httpContext.User.FindFirst("tenantId")?.Value ??
                           httpContext.User.FindFirst("tenant")?.Value;
                }
                return null;
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "获取当前租户ID时发生异常");
                return null;
            }
        }

        /// <summary>
        /// 获取当前用户IP地址
        /// </summary>
        public string? GetCurrentUserIpAddress()
        {
            try
            {
                var httpContext = _httpContextAccessor.HttpContext;
                if (httpContext != null)
                {
                    // 优先检查X-Forwarded-For头（代理/负载均衡器）
                    var forwardedFor = httpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault();
                    if (!string.IsNullOrEmpty(forwardedFor))
                    {
                        return forwardedFor.Split(',')[0].Trim();
                    }

                    // 检查X-Real-IP头
                    var realIp = httpContext.Request.Headers["X-Real-IP"].FirstOrDefault();
                    if (!string.IsNullOrEmpty(realIp))
                    {
                        return realIp;
                    }

                    // 使用连接的远程IP
                    return httpContext.Connection.RemoteIpAddress?.ToString();
                }
                return null;
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "获取当前用户IP地址时发生异常");
                return null;
            }
        }

        /// <summary>
        /// 获取当前用户User-Agent
        /// </summary>
        public string? GetCurrentUserAgent()
        {
            try
            {
                var httpContext = _httpContextAccessor.HttpContext;
                return httpContext?.Request?.Headers["User-Agent"].FirstOrDefault();
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "获取当前用户User-Agent时发生异常");
                return null;
            }
        }

        /// <summary>
        /// 检查当前用户是否为系统管理员
        /// </summary>
        public bool IsSystemAdmin()
        {
            return IsInRole("SystemAdmin") || IsInRole("Admin");
        }

        /// <summary>
        /// 检查当前用户是否为匿名用户
        /// </summary>
        public bool IsAnonymous()
        {
            try
            {
                var httpContext = _httpContextAccessor.HttpContext;
                return httpContext?.User?.Identity?.IsAuthenticated != true;
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "检查匿名用户状态时发生异常");
                return true;
            }
        }

        /// <summary>
        /// 获取用户Claims
        /// </summary>
        public Dictionary<string, string> GetUserClaims()
        {
            try
            {
                var httpContext = _httpContextAccessor.HttpContext;
                if (httpContext?.User?.Identity?.IsAuthenticated == true)
                {
                    return httpContext.User.Claims.ToDictionary(c => c.Type, c => c.Value);
                }
                return new Dictionary<string, string>();
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "获取用户Claims时发生异常");
                return new Dictionary<string, string>();
            }
        }
    }
}
